const express = require("express");
const mongoDB = require("../../models/db");
const http = require("http");
const server = http.createServer(express())
const io = require("socket.io");
module.exports = function(){
	var router = express.Router();
	router.get("/",(req,res)=>{
		res.render("chat.ejs",{"where":"chat",userInf:{
			login:req.session.login?req.session.login:false,
			username:req.session.username?req.session.username:'',
		}})
	});
	//获取聊天者的用户名
	//mongoDB.find('web','userInf',{})
	//存储登陆过的用户sock,用户名，头像
	//{
	//	sock:'',
	//	name:'',
	//	url:''
	//}
	let aSock = [];
	let wsServer = io.listen(server);
	wsServer.on("connection",(sock)=>{
		var current_name = null;
		//接受用户的名字
		sock.on("chatname",(name,imgurl)=>{
			aSock.push({
				sock:sock,
				name:name,
				url:imgurl
			});
			current_name = name;
			//改变用户的登录状态,上线
			mongoDB.changeData("weibo","userInf",{"useraccount":name},{"$set":{online:1}},(err,result)=>{
				if(err){
					console.log("修改数据错误");
				}else{
					console.log('下线');
				}
			});
		});
		//接收前台发来的信息
		sock.on("msg",(txt,name,url)=>{
			if(!txt){
				sock.emit("msg_ret",1,'内容不能为空')
			}else{
				sock.emit("msg_ret",0,'输入成功')
				aSock.forEach(item=>{
					if(item.sock==sock) return;
					item.sock.emit("msg",txt,name,url);
				});
			}
		});
		//离线处理
		sock.on("disconnect",()=>{
			//改变用户的登录状态,下线
			mongoDB.changeData("weibo","userInf",{"useraccount":current_name},{"$set":{online:0}},(err,result)=>{
				if(err){
					console.log("修改数据错误");
				}else{
					console.log('下线');
				}
			});
		})
	});
	server.listen(8089)
	return router;
}